﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media.Imaging;

namespace Wpf_Tool_ZC
{
    /// <summary>
    /// Wnd_Shot.xaml 的交互逻辑
    /// </summary>
    public partial class Wnd_Shot : Window
    {
        public Wnd_Shot()
        {
            InitializeComponent();
        }

        private void Click_Shot01(object sender, RoutedEventArgs e)
        {
            int iHWnd = 0;
            try
            {
                iHWnd = Convert.ToInt32(tbHWnd.Text.Trim(), 16);
            }
            catch
            {
                System.Windows.MessageBox.Show("窗口句柄转换错误");
                return;
            }
            if (iHWnd == 0)
            {
                System.Windows.MessageBox.Show("注意: 窗口句柄为0 ! ! !");
                return;
            }

            IntPtr p = (IntPtr)iHWnd;

            Bitmap bm = GetWindowBMP_01(p);

            if (bm != null)
            {
                IntPtr ptr = bm.GetHbitmap(); //obtain the Hbitmap
                BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    ptr,
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                DeleteObject(ptr); //release the HBitmap

                img01.Source = bs;
            }
            
        }

        public static Bitmap GetWindowBMP(IntPtr _hWnd)
        {
            IntPtr dc = GetWindowDC(_hWnd);
            Control control = Control.FromHandle(_hWnd);
            if (control == null)
            {
                unsafe
                {
                    sbyte[] bytes = new sbyte[256];
                    fixed (sbyte* pb = &bytes[0])
                    {
                        GetWindowText(_hWnd, pb, 256);
                        string str = new string(pb);
                        System.Windows.MessageBox.Show("窗口标题：\"" + str + "\", 获取失败");
                    }
                }
                return null;
            }
            IntPtr hbitmap = CreateCompatibleBitmap(dc, control.Width, control.Height);
            IntPtr memdc = CreateCompatibleDC(dc);
            SelectObject(memdc, hbitmap);
            PrintWindow(_hWnd, memdc, 0);
            Bitmap bmp = Bitmap.FromHbitmap(hbitmap);
            DeleteDC(dc);//删除用过的对象
            DeleteDC(memdc);//删除用过的对象
            return bmp;
        }

        public static Bitmap GetWindowBMP_01(IntPtr _hWnd)
        {
            IntPtr dc = GetWindowDC(_hWnd);

            User32.RECT windowRect = new User32.RECT();
            User32.GetWindowRect(_hWnd, ref windowRect);
            int width = windowRect.right - windowRect.left;
            int height = windowRect.bottom - windowRect.top;

            IntPtr hbitmap = CreateCompatibleBitmap(dc, width, height);
            IntPtr memdc = CreateCompatibleDC(dc);
            SelectObject(memdc, hbitmap);
            PrintWindow(_hWnd, memdc, 0);
            Bitmap bmp = Bitmap.FromHbitmap(hbitmap);
            DeleteDC(dc);//删除用过的对象
            DeleteDC(memdc);//删除用过的对象
            return bmp;
        }


        [DllImport("user32.dll", EntryPoint = "GetWindowText")]
        public unsafe static extern int GetWindowText(
            IntPtr hwnd,
            sbyte* pb,
            int cch
        );

        [DllImport("gdi32")]
        private static extern int DeleteObject(IntPtr p);


        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateDC(
            string lpszDriver,        // driver name驱动名
            string lpszDevice,        // device name设备名
            string lpszOutput,        // not used; should be NULL
            IntPtr lpInitData  // optional printer data
        );

        [DllImport("gdi32.dll")]
        public static extern int BitBlt(
            IntPtr hdcDest, // handle to destination DC目标设备的句柄
            int nXDest,  // x-coord of destination upper-left corner目标对象的左上角的X坐标
            int nYDest,  // y-coord of destination upper-left corner目标对象的左上角的Y坐标
            int nWidth,  // width of destination rectangle目标对象的矩形宽度
            int nHeight, // height of destination rectangle目标对象的矩形长度
            IntPtr hdcSrc,  // handle to source DC源设备的句柄
            int nXSrc,   // x-coordinate of source upper-left corner源对象的左上角的X坐标
            int nYSrc,   // y-coordinate of source upper-left corner源对象的左上角的Y坐标
            UInt32 dwRop  // raster operation code光栅的操作值
        );

        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleDC(
            IntPtr hdc // handle to DC
        );

        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleBitmap(
            IntPtr hdc,        // handle to DC
            int nWidth,     // width of bitmap, in pixels
            int nHeight     // height of bitmap, in pixels
        );

        [DllImport("gdi32.dll")]
        public static extern IntPtr SelectObject(
            IntPtr hdc,          // handle to DC
            IntPtr hgdiobj   // handle to object
        );

        [DllImport("gdi32.dll")]
        public static extern int DeleteDC(
            IntPtr hdc          // handle to DC
        );

        [DllImport("user32.dll")]
        public static extern bool PrintWindow(
            IntPtr hwnd,               // Window to copy,Handle to the window that will be copied. 
            IntPtr hdcBlt,             // HDC to print into,Handle to the device context. 
            UInt32 nFlags              // Optional flags,Specifies the drawing options. It can be one of the following values. 
        );

        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowDC(
            IntPtr hwnd
        );

        private void Click_Shot02(object sender, RoutedEventArgs e)
        {
            
        }
    }// class


    class User32
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        }
        [DllImport("user32.dll")]
        public static extern IntPtr GetDesktopWindow();
        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowDC(IntPtr hWnd);
        [DllImport("user32.dll")]
        public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
    }
}
